package com.systop.asset.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 二维码生成工具类
 */
@Component
public class QRCodeGenerator {

    @Value("${upload.qrcode-path}")
    private String qrCodeSavePath;

    /**
     * 生成二维码图片并返回文件路径
     *
     * @param text   二维码内容
     * @param width  图片宽度(像素)
     * @param height 图片高度(像素)
     * @return 生成的二维码图片路径
     * @throws IOException     文件操作异常
     * @throws WriterException 二维码生成异常
     */
    public String generateQRCode(String text, int width, int height) throws IOException, WriterException {
        // 创建存储目录
        Path path = Paths.get(qrCodeSavePath);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }

        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错级别
        hints.put(EncodeHintType.MARGIN, 1); // 边距
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 字符编码

        // 生成二维码矩阵
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 转换为BufferedImage
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + ".png";
        File qrFile = new File(qrCodeSavePath, fileName);

        // 保存图片
        ImageIO.write(bufferedImage, "PNG", qrFile);

        return qrFile.getAbsolutePath();
    }

    /**
     * 生成二维码并返回Base64编码
     *
     * @param text   二维码内容
     * @param width  图片宽度(像素)
     * @param height 图片高度(像素)
     * @return Base64编码的二维码图片
     */
    public String generateQRCodeBase64(String text, int width, int height) {
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            ImageIO.write(bufferedImage, "PNG", os);
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(os.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }
}

